package handle

import (
	"context"
	participate "gitee.com/jinmingzhi/cdce-service/api/protos/participate/v1alpha"
	"gitee.com/jinmingzhi/cdce-service/internal/model"
	"gitee.com/jinmingzhi/cdce-service/internal/service"
	"github.com/golang/protobuf/ptypes/empty"
)

var (
	times = []string{
		"2020-12-08 08:00 ~ 2020-12-08 09:30",
		"2020-12-08 10:00 ~ 2020-12-08 11:30",
		"2020-12-08 14:00 ~ 2020-12-08 15:30",
		"2020-12-08 16:00 ~ 2020-12-08 17:30",

		"2020-12-09 08:00 ~ 2020-12-09 09:30",
		"2020-12-09 10:00 ~ 2020-12-09 11:30",
		"2020-12-09 14:00 ~ 2020-12-09 15:30",
		"2020-12-09 16:00 ~ 2020-12-09 17:30",
	}
)

type Participate struct {
	courseSvc       service.Course
	areaSvc         service.Area
	schoolReportSvc service.SchoolReport
}

func NewParticipate(courseSvc service.Course, areaSvc service.Area, schoolReportSvc service.SchoolReport) *Participate {
	return &Participate{schoolReportSvc: schoolReportSvc, areaSvc: areaSvc, courseSvc: courseSvc}
}

// 前期确认
func (p *Participate) PrepareConfirm(ctx context.Context, _ *empty.Empty) (*empty.Empty, error) {
	return &empty.Empty{}, nil
}

// 课程
func (p *Participate) Subject(ctx context.Context, _ *empty.Empty) (*participate.SubjectResp, error) {
	data, err := p.courseSvc.FindAll(ctx)
	if err != nil {
		return nil, handlerErr(err)
	}

	return modelsToPbSubjectResp(data), nil
}

// 学校
func (p *Participate) School(ctx context.Context, req *participate.SchoolReq) (*participate.SchoolResp, error) {
	data, err := p.areaSvc.FindSchoolByCourseID(ctx, req.SubjectId)
	if err != nil {
		return nil, handlerErr(err)
	}
	return modelsToPbSchoolResp(data), nil
}

// 学校报考时间
func (p *Participate) SchoolTime(ctx context.Context, req *participate.SchoolTimeReq) (*participate.SchoolTimeResp, error) {
	return &participate.SchoolTimeResp{Times: times}, nil
}

// 选择报考时间
func (p *Participate) SchoolTimeconfirm(ctx context.Context, req *participate.SchoolTimeConfigReq) (*empty.Empty, error) {
	return &empty.Empty{}, nil
}

// 报考确认
func (p *Participate) Confirm(ctx context.Context, req *participate.Confirm) (*empty.Empty, error) {
	uid, err := GetUid(ctx)
	if err != nil {
		return nil, handlerErr(err)
	}

	school_reports := make([]*model.SchoolReport, 0)
	pays := make([]*model.Pay, 0)
	for _, v := range req.Data {
		school_reports = append(school_reports, model.NewSchoolReport(uid, 1, v.CourseId, v.SchoolId, v.Time))
		pays = append(pays, model.NewPay(uid, 1, v.Time))
	}
	err = p.schoolReportSvc.Add(ctx, school_reports, pays)
	if err != nil {
		return nil, err
	}
	return &empty.Empty{}, nil
}
